#!/usr/bin/env bash
# Find commits by https://github.com/fedya/updates_tracker
# that might have broken specs duit to lack of validation

# https://devhints.io/git-log-format

if [ -z "$REPO_DIR" ]; then
	echo 'Define $REPO_DIR!'
	exit 1
fi

set -efu
export PAGER=none
result_csv="$(mktemp)"
LIST="${LIST:-$(find "$REPO_DIR" -maxdepth 1 -type d | grep -v "$REPO_DIR\$" | sed -e 's,^./,,g' -e '/^.$/d' | sort -u)}"
# e.g. GIT_AFTER="Jan 25 2020"
# TODO: fix it, it does not work
GIT_AFTER="${GIT_AFTER:-}"
git_log="git log"
if [ -n "$GIT_AFTER" ]
	then git_log="${git_log} --after=${GIT_AFTER}"
fi

_log_commit() {
	echo "${git_repo};${commit_hash};https://abf.io/import/$(echo "${git_repo}" | awk -F '/' '{print $NF}')/commit/${commit_hash}" | tee -a "$result_csv"
}

while read -r git_repo
do
	pushd "${REPO_DIR}/${git_repo}"
	while read -r line
	do
		if echo "$line" | grep -q 'version autoupdate \['; then
			commit_hash="$(echo "$line" | grep 'version autoupdate \[' | head -n 1 | awk -F ':' '{print $1}')"
			# find commits where Version contained macros, they usually break packages
			if git diff ${commit_hash}~ ${commit_hash} | grep -E '^-Version:|^-Release:' | grep -q '%' || \
				[ "$(git diff-tree --no-commit-id --name-only -r "${commit_hash}" | wc -l)" -lt 2 ]
				then _log_commit && continue
			fi
			# if .abf.yml has not changed, than it is a bad commit
			if ! git diff ${commit_hash}~ ${commit_hash} .abf.yml > /dev/null 2>&1 ; then
				_log_commit && continue
			fi
			# find commits where hash in .abf.yml has not changed - they are definitely incorrect
			yml_diff="$(git diff ${commit_hash}~ ${commit_hash} .abf.yml)"
			old_hash="$(echo "$yml_diff" | grep '^-' | grep ': ' | sed -e 's,\",,g' | awk -F ': ' '{print $NF}')"
			new_hash="$(echo "$yml_diff" | grep '^+' | grep ': ' | sed -e 's,\",,g' | awk -F ': ' '{print $NF}')"
			if [ -z "$old_hash" ] || [ -z "$new_hash" ]; then continue; fi
			if [ "$old_hash" = "$new_hash" ]; then
				_log_commit && continue
			fi
		fi
	done < <(${git_log} --pretty="format:%H:%ce:%s" ; echo)
	popd
done < <(echo "$LIST")

echo ""
echo "RESULT in CSV: $result_csv"
